<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\XiaofeoResource;
use App\model\Project;
use App\model\Source;
use App\model\TuiguangSource;
use App\model\Xiaofei;
use App\Repository\WechatRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Carbon;

class XiaofeiController extends Controller
{
    /**
     * 查询消费
     *@authenticated
     * @bodyParam project_id int required  项目id. Example:null
     * @bodyParam created_at time required 查询日期分0时 Example:2019-3-15 00:00:00
     */
    public function xiaofei(Request $request){
        $project=Project::findOrFail($request->get('project_id'));
        $source=$project->source;
        $array=[];
       foreach ($source as $value){
           $xiaofei=Xiaofei::whereProjectId($request->get('project_id'))
               ->where('source_id',$value->source_id)
               ->whereDate('created_at',$request->get('created_at',Carbon::today()))
               ->first();
           if (!$xiaofei){
               $xiaofei= new Xiaofei();
               $xiaofei->source_id=$value->source_id;
               $xiaofei->project_id=$request->get('project_id');
               $xiaofei->created_at=$request->get('created_at',Carbon::today());
               $xiaofei->save();
           }
            $array[]=array_merge($xiaofei->toArray(),$value->toArray());
       }


       $result= [
           'project'=>$project->toArray(),
           'tuiguang'=>$array,
       ];

        return new XiaofeoResource(collect($result));
    }
    /**
     *提交消费
     */
    public function xiaofeiSubmit(Request $request){
         $tuiguang= $request->get('tuiguang');
         $tuiguang=json_decode($tuiguang,true);
        $true=true;
         foreach ($tuiguang as $value){
             $xiaofei=  Xiaofei::find($value['id']);
             $xiaofei->xiaofei=$value['xiaofei'] ?? null;
             $xiaofei->hit=$value['hit'] ?? null;
             $xiaofei->save();
             if ($value['xiaofei']!==''){

             }else{
                 $true=false;
             }
             $time=$xiaofei->created_at;
         }
         if ($true==true){
             $wechat=new WechatRepository();
             $wechat->sendBaobiaoMessage(\Auth::guard('api')->user(),Project::find($xiaofei->project_id),$time);
         }
          return response()->json([
              'status' => 1,
              'message'=>'保存成功',
          ]);
    }

}
